<template>
  <div>
    <avue-crud
      :option="selectOption"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      v-model="form"
      ref="crud"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot="menuLeft">
        <el-button type="primary" size="small" icon="el-icon-plus" v-if="permission.stationPriceConfig_add" @click="handleAdd">新 增</el-button>
        <el-button type="danger" size="small" icon="el-icon-delete" v-if="permission.stationPriceConfig_delete" plain @click="handleDelete" :disabled="isBtnDisabled"
          >作 废</el-button
        >
        <el-button type="warning" size="small" icon="el-icon-setting" v-if="permission.stationPriceConfig_audit" @click="handleAudit" v-preventReClick :disabled="isBtnDisabled"
          >审核</el-button
        >
        <el-button type="success" size="small" icon="el-icon-upload2" v-if="permission.stationPriceConfig_import" @click="handleImport" v-preventReClick>导入</el-button>
      </template>
      <!-- 操作列 -->
      <template slot="menu" slot-scope="{ row }">
        <el-button type="text" size="small" icon="el-icon-view" v-if="permission.stationPriceConfig_view" @click="handleView(row)">详情</el-button>
        <el-button type="text" size="small" icon="el-icon-edit" v-if="permission.stationPriceConfig_edit" @click="handleEdit(row)">编辑</el-button>
        <el-button type="text" size="small" icon="el-icon-delete" v-if="permission.stationPriceConfig_delete" @click="handleDelete(row)" :disabled="row.status === 3">
          作废</el-button
        >
      </template>
    </avue-crud>
    <el-dialog
      append-to-body
      width="60%"
      top="5vh"
      :title="stationPriceDialog.title"
      :visible.sync="stationPriceDialog.visible"
      @open="stationPriceDialogOpen"
      @close="stationPriceDialogClose"
    >
      <div class="sail-header-dialog-content pd-12">
        <!-- 基本信息 -->
        <!--        <div-->
        <!--          :element-loading-text="stationPriceDialogLoadingText"-->
        <!--          v-loading="stationPriceDialogLoading"-->
        <!--          element-loading-spinner="el-icon-loading"-->
        <!--          element-loading-background="#ffffffe6"-->
        <!--        >-->
        <h1 class="subTitle"><i class="el-icon-vertical-bar mr10"></i>基本信息</h1>
        <avue-form v-model="stationPriceDialog.basicInfoFormModel" ref="basicInfoForm" key="basicInfoFormKey" :option="stationPriceDialog.basicInfoFormOptions"> </avue-form>
        <!-- 工站单价 -->
        <h1 class="subTitle"><i class="el-icon-vertical-bar mr10"></i>工段单价</h1>
        <avue-crud
          ref="stationPriceCrud"
          v-model="stationPriceDialog.form"
          :option="stationPriceDialog.option"
          :table-loading="stationPriceDialog.loading"
          :data="stationPriceDialog.data"
          :defaults.sync="stationPriceDialog.defaults"
          @row-update="rowPriceUpdate"
          @row-del="handleDelPriceRow"
        >
        </avue-crud>
        <!-- 合计 -->
        <h1 class="subTitle"></h1>
        <avue-form v-model="stationPriceDialog.amountFormModel" ref="amountForm" key="amountFormKey" :option="stationPriceDialog.amountFormOptions"> </avue-form>
        <!--        </div>-->
        <!-- 工站单价 -->
        <h1 class="subTitle" v-if="isViewButtonStatus"><i class="el-icon-vertical-bar mr10"></i>所有版本</h1>
        <avue-crud v-if="isViewButtonStatus" ref="stationPriceCrud" :option="versionOption" :data="versionData">
          <template slot="menu" slot-scope="{ row }">
            <el-button type="text" size="small" icon="el-icon-view" @click="handleSetCurrentVersion(row)" :disabled="currentVersion === row.version">
              {{ currentVersion === row.version ? '当前版本' : '查看' }}
            </el-button>
          </template>
        </avue-crud>
      </div>
      <div slot="footer" class="dialog-footer" v-if="!isViewButtonStatus">
        <el-button size="small" icon="el-icon-circle-close" @click="closeDialog">取 消</el-button>
        <el-button type="primary" size="small" icon="el-icon-circle-plus-outline" @click="submitForm" v-preventReClick>保 存</el-button>
      </div>
    </el-dialog>
    <global-modal-template :visibile.sync="visibile" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"> </global-modal-template>
    <importDialogComp
      title="工段单价导入"
      url="/api/mes-product/product-section-price/import"
      export-name="工段单价配置导入模板.xlsx"
      :visible.sync="importConfigVisble"
      @submit="codeClose"
    ></importDialogComp>
  </div>
</template>

<script>
import { mapGetters } from 'vuex';
import {
  cancellation,
  cancellationSection,
  sectionEdit,
  getSectionList,
  sectionPriceAudit,
  sectionDetail,
  getDetail,
  processProductRouteByPartno,
  getSection
} from '@/api/product/stationPriceConfig';
import globalModalTemplate from '@/components/common-modal-template/global-modal-template';
import importDialogComp from '@/components/dialog/import/index.vue';

export default {
  name: 'selectionPrice',
  components: {
    globalModalTemplate,
    importDialogComp
  },
  data() {
    return {
      importConfigVisble: false,
      tableOption: {},
      visibile: false,
      timer: new Date().getTime(),
      stationPriceDialogLoading: false,
      selectOption: {
        height: 'calc(100vh - 480px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        indexLabel: '序号',
        viewBtn: false,
        editBtn: false,
        delBtn: false,
        addBtn: false,
        menu: true,
        menuWidth: 200,
        selection: true,
        labelWidth: 120,
        dialogClickModal: false,
        columnBtn: false,
        column: [
          {
            label: '产品名称',
            prop: 'partName',
            search: true
          },
          {
            label: '产品编码',
            prop: 'partNo',
            search: true
          },
          {
            label: '产品型号',
            prop: 'partModel',
            type: 'search',
            disabled: true
          },
          {
            label: '版本',
            prop: 'version'
          },
          {
            label: '总价',
            prop: 'totalPrice',
            disabled: true
          },
          {
            label: '系数',
            prop: 'rate',
            type: 'search',
            minRows: 0,
            disabled: true,
            searchType: 'input'
          },
          {
            label: '折后总价',
            prop: 'discountedPrice'
          },
          {
            label: '有效期',
            prop: 'effectiveTime',
            width: 200,
            formatter: (val) => {
              return val.effectiveFrom || '' + ' 至 ' + val.effectiveFrom || '';
            }
          },
          {
            label: '状态',
            prop: 'status',
            width: 100,
            search: true,
            type: 'select',
            minRows: 3,
            span: 24,
            dicData: [
              { label: '已审核', value: 1 },
              { label: '未审核', value: 0 },
              { label: '已作废', value: 3 },
              { label: '已失效', value: 4 }
            ],
            html: true,
            formatter: (val) => {
              switch (val.status) {
                case 4:
                  return `<span class="stateWords-warning">已失效</span>`;
                case 3:
                  return `<span class="stateWords-default">已作废</span>`;
                case 1:
                  return `<span class="stateWords-success">已审核</span>`;
                case 0:
                  return `<span class="stateWords-danger">未审核</span>`;
                default:
                  break;
              }
            }
          }
        ]
      },
      data: [],
      form: {},
      loading: false,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      stationPriceDialog: {
        visible: false,
        title: '新 增',
        // 基本信息
        basicInfoFormModel: {},
        basicInfoFormOptions: {
          submitBtn: false,
          emptyBtn: false,
          column: [
            {
              label: '产品编码',
              prop: 'partNo',
              searchType: 'input',
              type: 'search',
              disabled: true,
              rules: [
                {
                  required: true,
                  message: '请输入产品编码',
                  trigger: 'blur'
                }
              ],
              appendClick: () => {
                if (this.isViewButtonStatus) return;
                this.openUserCommonModal({
                  type: 'partNo'
                });
              }
            },
            {
              label: '产品名称',
              disabled: true,
              prop: 'partName'
            },
            {
              label: '产品型号',
              disabled: true,
              prop: 'partModel'
            },
            {
              label: '有效期',
              prop: 'effective',
              type: 'daterange',
              format: 'yyyy-MM-dd',
              valueFormat: 'yyyy-MM-dd',
              startPlaceholder: '日期开始范围自定义',
              endPlaceholder: '日期结束范围自定义',
              rules: [
                {
                  required: true,
                  message: '请选择有效期'
                  // trigger: 'blur'
                }
              ]
            }
          ]
        },
        // 工站单价
        form: {},
        option: {
          tip: false,
          height: 300,
          calcHeight: 30,
          maxHeight: 300,
          searchShow: true,
          searchMenuSpan: 6,
          border: true,
          index: false,
          addBtn: false,
          editBtn: true,
          delBtn: true,
          viewBtn: false,
          refreshBtn: false,
          rowKey: 'id',
          rowParentKey: 'parentId',
          // cellBtn: true,
          columnBtn: false,
          menu: true,
          menuWidth: 250,
          selection: false,
          dialogClickModal: false,
          column: [
            {
              label: '工段名称',
              prop: 'sectionName',
              addDisplay: false,
              editDisplay: false
            },
            {
              label: '加工内容',
              prop: 'processingContent',
              span: 24
            },
            {
              label: '工段单价',
              prop: 'sectionPrice',
              type: 'number',
              value: 0,
              precision: 2,
              span: 24,
              minRows: 0,
              rules: [
                {
                  required: true,
                  message: '请输入工站单价',
                  trigger: 'blur'
                }
              ]
            },
            {
              label: '备注',
              prop: 'remark',
              type: 'textarea',
              span: 24,
              minRows: 3,
              maxRows: 3,
              cell: true
            }
          ]
        },
        query: {
          shiftGroupId: ''
        },
        selectionList: [],
        loading: false,
        defaults: {},
        submitData: null,
        data: [],
        // 金额合计
        amountFormModel: {},
        amountFormOptions: {
          submitBtn: false,
          emptyBtn: false,
          column: [
            {
              label: '合计',
              prop: 'totalPrice',
              type: 'number',
              controls: false,
              span: 8,
              disabled: true,
              labelWidth: 60
            },
            {
              label: '系数',
              prop: 'rate',
              type: 'number',
              disabled: false,
              span: 8,
              value: 100,
              min: 0,
              precision: 0,
              controls: false,
              labelWidth: 60,
              rules: [
                {
                  required: true,
                  message: '请输入系数',
                  trigger: 'blur'
                }
              ],
              blur: ({ value, column }) => {
                if (value) {
                  this.changeRate(value);
                }
              }
            },
            {
              label: '折后总价',
              prop: 'discountedPrice',
              type: 'number',
              disabled: true,
              controls: false,
              span: 8,
              labelWidth: 80
            }
          ]
        }
      },
      currentVersion: '',
      versionOption: {
        index: true,
        indexLabel: '序号',
        menu: true,
        viewBtn: false,
        editBtn: false,
        delBtn: false,
        addBtn: false,
        columBtn: false,
        refreshBtn: false,
        border: true,
        column: [
          {
            label: '版本',
            prop: 'version'
          },
          {
            label: '编辑人',
            prop: 'editor'
          },
          {
            label: '编辑时间',
            prop: 'editTime'
          },
          {
            label: '审核人',
            prop: 'approveName'
          },
          {
            label: '审核时间',
            prop: 'approveTime'
          }
        ]
      },
      versionData: []
    };
  },
  computed: {
    ...mapGetters(['permission']),
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    },
    isBtnDisabled() {
      return this.selectionList.length === 0;
    },
    isViewButtonStatus() {
      return this.stationPriceDialog.title === '详 情';
    },
    isEditButtonStatus() {
      return this.stationPriceDialog.title === '编 辑';
    },
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.stationPriceConfig_add, false),
        viewBtn: this.vaildData(this.permission.stationPriceConfig_view, false),
        delBtn: this.vaildData(this.permission.stationPriceConfig_delete, false),
        editBtn: this.vaildData(this.permission.stationPriceConfig_edit, false),
        auditBtn: this.vaildData(this.permission.stationPriceConfig_audit, false)
      };
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
  },
  methods: {
    codeClose(value) {
      if (value) {
        this.onLoad(this.page);
      }
    },
    rowSave(row, done, loading) {
      add(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
        }
      );
    },
    rowDel(row) {
      this.$confirm('确定将选择数据作废?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return cancellation([row.id]);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    handleAdd() {
      this.handleType('新 增', false);
      delete this.stationPriceDialog.basicInfoFormModel.id;
    },
    handleType(name, status) {
      this.stationPriceDialog.visible = true;
      this.stationPriceDialog.title = name;
      this.stationPriceDialog.option.menu = !status; // 操作列
      let columns = this.stationPriceDialog.basicInfoFormOptions.column;
      let effective = columns.findIndex((c) => c.prop == 'effective');
      this.$nextTick(() => {
        columns[effective].disabled = status;
        // 合计：系数
        this.$set(this.stationPriceDialog.amountFormOptions.column[1], 'disabled', status);
      });
    },
    handleDelete(row) {
      this.$confirm('确定将选择数据作废?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return cancellationSection(row.id || this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '作废成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    handleAudit() {
      const isCanAudit = this.selectionList.every((el) => el.status === 0);
      if (!isCanAudit) {
        this.$message.warning('当前勾选信息中存在已审核/已失效/已作废信息，请重新选择。');
        return;
      }
      this.$confirm('是否确认将勾选的产品工段单价审核通过?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return sectionPriceAudit(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '审核成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getSectionList(page.currentPage, page.pageSize, Object.assign(params, this.query))
        .then((res) => {
          const data = res.data.data;
          this.page.total = data.total;
          if (data.records) {
            this.data = data.records;
          }
          this.selectionClear();
        })
        .finally(() => {
          this.loading = false;
        });
    },
    handleImport() {
      this.importConfigVisble = true;
    },
    closeDialog() {
      this.stationPriceDialogClose();
    },
    rowPriceUpdate(row, index, done, loading) {
      const currentData = this.stationPriceDialog.data[index];
      this.stationPriceDialog.data.splice(index, 1, Object.assign(currentData, row));
      try {
        const totalPrice = this.calculateSectionPriceSum(this.stationPriceDialog.data);
        this.stationPriceDialog.amountFormModel.totalPrice = totalPrice;
        this.stationPriceDialog.amountFormModel.discountedPrice = this.multiplyWithInteger(totalPrice, this.stationPriceDialog.amountFormModel.rate);
      } catch (e) {
        console.log(e);
      }
      done();
    },
    multiplyWithInteger(decimal, integer) {
      const multiplier = 100; // 将小数转换为整数的倍数
      const decimalInteger = Math.round(decimal * multiplier); // 将小数乘以倍数并四舍五入为整数
      console.log((decimalInteger * integer) / multiplier);
      return (decimalInteger * integer) / (multiplier * 100); // 将整数乘以正整数，并将结果除以倍数恢复为两位小数
    },
    calculateSectionPriceSum(data) {
      return data
        .reduce((sum, row) => {
          const sectionPrice = row.sectionPrice ? parseFloat(row.sectionPrice) : 0;
          return sum + sectionPrice;
        }, 0)
        .toFixed(2);
    },
    handleDelPriceRow(row, index) {
      this.stationPriceDialog.data.splice(index, 1);
    },

    changeRate(val) {
      const totalPrice = this.stationPriceDialog.amountFormModel.totalPrice;
      this.stationPriceDialog.amountFormModel.discountedPrice = this.multiplyWithInteger(totalPrice, this.stationPriceDialog.amountFormModel.rate);
    },
    submitForm() {
      const that = this;
      that.$refs['basicInfoForm'].validate((valid, done) => {
        if (valid) {
          done();
          that.$refs['amountForm'].validate(async (valid, done) => {
            if (valid) {
              if (this.stationPriceDialog.data && this.stationPriceDialog.data.length == 0) {
                that.$message.warning('工段单价配置不能为空');
                done();
                return;
              }
              const data = {
                ...this.stationPriceDialog.basicInfoFormModel,
                ...this.stationPriceDialog.amountFormModel
              };
              data.effectiveFrom = this.stationPriceDialog.basicInfoFormModel.effective[0];
              data.effectiveTo = this.stationPriceDialog.basicInfoFormModel.effective[1];
              delete data.effective;
              data.sectionPriceDetailList = this.stationPriceDialog.data;
              try {
                await sectionEdit(data);
                const msg = that.isEditButtonStatus ? '编辑成功' : '新增成功';
                this.$message.success(msg);
                this.stationPriceDialogClose();
                this.onLoad(this.page);
              } catch (e) {
                console.log(e);
              } finally {
                done();
              }
            }
          });
        }
      });
    },
    // 工站单价弹窗关闭
    stationPriceDialogClose() {
      this.$refs.basicInfoForm && this.$refs.basicInfoForm.resetForm();
      this.$refs.amountForm && this.$refs.amountForm.resetForm();
      this.stationPriceDialog.amountFormModel.rate = 100;
      this.stationPriceDialog.visible = false;
    },
    // 工站单价弹窗打开
    stationPriceDialogOpen() {
      this.routeList = [];
      this.processId = '';
      this.stationPriceDialog.data = [];
      // this.stationPriceOnLoad();
    },
    // 查看
    handleView(row) {
      this.$set(this.stationPriceDialog.basicInfoFormOptions.column[3], 'disabled', true);
      this.$set(this.stationPriceDialog.amountFormOptions.column[1], 'disabled', true);
      this.currentVersion = row.version;
      this.handleType('详 情', true);
      this.getDetailData(row.id);
    },
    handleSetCurrentVersion(row) {
      this.currentVersion = row.version;
      this.getDetailData(row.workSectionPriceId);
    },
    // 编辑
    handleEdit(row) {
      this.$set(this.stationPriceDialog.amountFormOptions.column[1], 'disabled', false);
      this.$set(this.stationPriceDialog.basicInfoFormOptions.column[3], 'disabled', false);
      this.handleType('编 辑', false);
      this.getDetailData(row.id);
    },
    async getDetailData(id) {
      // this.stationPriceDialogLoadingText = '数据加载中，请稍后...';
      try {
        const res = await sectionDetail(id);
        const data = res.data.data;
        if (data) {
          const {
            id,
            effectiveTo,
            effectiveFrom,
            partNo,
            partName,
            partModel,
            rate,
            totalPrice,
            discountedPrice,
            productSectionPriceDetailList = [],
            productSectionPriceVersionList = []
          } = data;
          this.stationPriceDialog.basicInfoFormModel = {
            id,
            partNo,
            partName,
            partModel,
            effective: [effectiveFrom, effectiveTo]
          };
          this.stationPriceDialog.amountFormModel = {
            rate,
            totalPrice,
            discountedPrice
          };
          this.stationPriceDialog.data = productSectionPriceDetailList;
          this.versionData = productSectionPriceVersionList;
          this.stationPriceDialogLoading = true;
        }
      } catch (e) {
        console.warn(e);
      }
    },
    openUserCommonModal(params) {
      let { type } = params;
      switch (type) {
        // 产品编码
        case 'partNo':
          this.modalName = 'partNoModal';
          this.visibile = true;
          this.tableOption = {
            modalTitle: '选择产品信息（双击进行选择）',
            url: '/api/mes-product/section/get-semifinished-work-section',
            isPage: true,
            rowSelectionType: 'single',
            menuWidth: 100,
            templateName: 'FILTERPARTMASTER'
          };
          break;
        default:
          break;
      }
    },
    // 获取选择的模态框行数据
    async getSelectedRows(rowData) {
      switch (this.modalName) {
        case 'partNoModal':
          this.visibile = false;
          this.stationPriceDialog.basicInfoFormModel.partNo = this._get(rowData, 'partNo', '');
          this.stationPriceDialog.basicInfoFormModel.partName = this._get(rowData, 'partName', '');
          this.stationPriceDialog.basicInfoFormModel.partModel = this._get(rowData, 'partModel', '');
          // 根据产品编码，查询产品工艺
          await this.getSectionByPartNoByPartNo(this.stationPriceDialog.basicInfoFormModel.partNo);
          break;
        default:
          break;
      }
    },
    async getSectionByPartNoByPartNo(partNo) {
      try {
        const res = await getSection(partNo);
        const record = (res.data.data && res.data.data.records) || [];
        if (record && record.length > 0) {
          const section = record[0].sections.map((i) => ({ sectionName: i.sectionName }));
          this.stationPriceDialog.data = section;
        } else {
          this.stationPriceDialog.data = [];
        }
      } catch (e) {}
    },
    newKey() {
      this.timer = new Date().getTime();
    }
  }
};
</script>

<style scoped lang="scss">
.subTitle {
  font-size: 16px;
  font-weight: bold;
  color: rgba(0, 0, 0, 0.85);

  .mr10 {
    margin-right: 10px;
  }
}

.sail-header-dialog-content {
  ::v-deep .avue-crud__menu {
    display: none;
  }
}
.pd-12 {
  padding: 12px;
}
</style>
